package team.bluepen.order.web.servlet.user;

import team.bluepen.order.ErrorPack;
import team.bluepen.order.constant.Constant;
import team.bluepen.order.constant.ErrorCode;
import team.bluepen.order.data.database.mysql.UserRepository;
import team.bluepen.order.data.entity.User;
import team.bluepen.order.web.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Kai
 */
@WebServlet(name = "UserLoginServlet", urlPatterns = "/api/user/login")
public class UserLoginServlet extends BaseServlet {
    public static final String USERNAME_PARAM = "username";
    public static final String PASSWORD_PARAM = "password";
    private final UserRepository repository = new UserRepository();

    @Override
    public void init() {
        repository.createAdmin();
    }

    @Override
    protected void post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter(USERNAME_PARAM);
        String password = req.getParameter(PASSWORD_PARAM);
        HttpSession session = req.getSession();
        setJsonHeader(resp);
        User user = new User()
                .setUsername(username)
                .setPassword(password);
        ErrorCode errorCode = repository.verifyUser(user);
        session.setAttribute(Constant.SESSION_USER, user);
        ErrorPack pack = new ErrorPack(errorCode, errorCode.toString());
        writeJson(resp, pack.toCodePack());
    }

    @Override
    protected boolean isCheckLogin() {
        return false;
    }
}
